<?php

namespace App\Http\Controllers;

use App\Http\Models\Album;
use App\Http\Models\Photo;
use App\Http\Models\User;
use App\Http\Models\UserAlbum;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;


class PhotoController extends Controller
{
    /*
     * 获取某个相册下的所有照片
     */
    public function index()
    {
        $album_id = request('album_id');
        //获取所有的相册
//      $res = Photo::where('album_id',$album_id)->groupBy('user_id')->get();
        $albums = Photo::with('user')->where('album_id',$album_id)->orderBy('created_at')->get();
        $photo_num = Album::find($album_id)['photo_num'];

        //照片列表的头像和时间
        $users = [];
        //头像显示
        $userAlbums = UserAlbum::where('album_id',$album_id)->get();
        $user_ids = [];
        foreach ($userAlbums as $item){
            $user_ids[] = $item->user_id;
        }
        $avatars = User::whereIn('id',$user_ids)->get();
        //定义一个相册数组
        $new_albums = [];
        //根据不同的用户分组获取对应照片
        foreach ($albums as $item)
        {
            $users[$item->user_id]['time'] = $item->created_at->toDateString();
            $users[$item->user_id]['avatar'] = $item->user?$item->user->avatar:'';
            $photo = asset($item->url);

            $new_albums[$item->user_id]['photos'][$item->id] = $photo;
        }

        $new_albums = [
           'photo_num'=>$photo_num,
           'album'=>$new_albums,
           'users'=>$users,
           'avatars' => $avatars
       ];
        if(!$albums)
        {
            return api_return('0','暂时没有照片',$albums);
        }

        return api_return(1,'成功获取照片',$new_albums);
    }

    /*
     * 添加照片路径到数据库
     */
    private function store($url){
        $album_id = request('album_id');
        $user_id = request('user_id');
        Photo::create(['url'=>$url,'album_id'=>$album_id,'user_id'=>$user_id]);
        Album::where('id',$album_id)->increment('photo_num');
    }

    /*
    * 上传相片
    */
    public function upload(Request $request){
        if(!$file = $request->file('file')){
            $file = $request->file('file');         //前端框架默认key=file
        }
        $fileTypes = array('jpg', 'jpeg', 'png', 'gif');      // 允许上传类型
        $max_size = 2048000;
        // 本地上传
        if (empty($file)) {
            return api_return(false, '上传失败，文件为空！');
        }
        if (in_array($file->extension(), $fileTypes)) {
            if ($file->getClientSize() <= $max_size) {
                // 图片处理
                $fileName = time() . uniqid() . str_random(4) . '.' . $file->extension();
                $subDir = date('Ym');

                if(!is_dir(public_path("img/$subDir"))){
                    Storage::disk('public')->makeDirectory("img/$subDir");
                }

                $path = '/img' . "/$subDir/" . $fileName;
                $realPath = $file->getRealPath();

                Storage::disk('public')->put($path,file_get_contents($realPath));

                //保存文件路径到数据库
                $this->store($path);
                return api_return(true, '图片上传成功！', ['asset_url' => asset($path), 'images' => $path]);
            } else {
                return api_return(false, '上传失败，文件大小超过' . $max_size . '字节');
            }
        } else {
            return api_return(false, '只允许上传' . json_encode($fileTypes) . '格式文件');
        }

    }

    /*获取相册下的照片，限制三张*/
    public function getPhotos(){
        $arr = [];

        $album_id = request('album_id');
        $album_name = Album::find($album_id)['name'];
        $photos = Photo::where('album_id',$album_id)->limit(3)->get(['url']);
        $new_photos = [];
        foreach ($photos as $photo){
            $new_photos[] = asset($photo['url']);
        }
        $arr['album_name'] = $album_name;
        $arr['photos'] = $new_photos;
        return api_return(1,'获取成功',$arr);
    }

    /*
     * 删除相片
     */
    public function delPhoto(){
        $photo_ids = request('photo_ids');
        $album_id = request('album_id');
        //删除照片
        $res = Photo::whereIn('id',$photo_ids)->delete();
        //相册照片数量减少
        Album::where('id',$album_id)->decrement('photo_num',count($photo_ids));
        if(!$res){
            return api_return(0,'删除失败',[]);
        }
        return api_return(1,'删除成功',$res);
    }

    /*
     * 下载图片
     */
    public function download(){

    }
}
